package com.hspedu.streamtest;

import com.hspedu.lambda2.Employee;
import com.hspedu.lambda2.EmployeeData;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/3/30
 * @time 15:14
 */
public class StreamAPITest1 {

    /**
     * 筛选与切片
     */
    @Test
    public void test1(){
        List<Employee> employees = EmployeeData.getEmployees();
        //filter(Predicate p) 接收lambda，从流中排除某些元素
        Stream<Employee> employeeStream = employees.stream();
        employeeStream.filter(employee -> employee.getSalary() > 7000)
                .forEach(employee -> System.out.println(employee));
        System.out.println();

        //limit(n) 截断流，使流中的元素不超过指定的数量
        employees.stream().limit(3).forEach(System.out :: println);
        System.out.println();
        //skip(n) 跳过元素，返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个，则返回一
        //个空流。与 limit(n) 互补
        employees.stream().skip(3).forEach(System.out :: println);

        System.out.println();
        //distinct() 筛选，通过流所生成元素的 hashCode() 和 equals() 去除重复元素
        employees.add(new Employee(1010,"刘强东",40,8000));
        employees.add(new Employee(1010,"刘强东",41,8000));
        employees.add(new Employee(1010,"刘强东",40,8000));
        employees.add(new Employee(1010,"刘强东",40,8000));
        employees.add(new Employee(1010,"刘强东",40,8000));
        employees.stream().distinct().forEach(System.out :: println);
    }

    /**
     * 映射
     */
    @Test
    public void test2(){
        List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
        Stream<String> stream = list.stream();
        stream.map(s -> s.toUpperCase()).forEach(System.out :: println);

        //获取姓名长度大于三的员工的姓名
        List<Employee> employees = EmployeeData.getEmployees();
        Stream<Employee> employeeStream = employees.stream();
        //将employees 根据 getName 函数映射 得到一个新的名字集合
        employeeStream.map(Employee::getName).filter(name -> name.length() > 3).forEach(System.out::println);

        //接收一个函数作为参数，将流中的每个值都换成另
        //一个流，然后把所有流连接成一个流
        Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream);
        characterStream.forEach(System.out::println);
    }

    public static Stream<Character> fromStringToStream(String str){
        ArrayList<Character> arrayList = new ArrayList();
        for (char c : str.toCharArray()) {
            arrayList.add(c);
        }
        return arrayList.stream();
    }

        /**
         * 排序
         */
        @Test
        public void test3(){
            List<Integer> nums = Arrays.asList(1, 3, 99, 100, 32, 4, -21);
            nums.stream().sorted().forEach(System.out :: println);

            List<Employee> employees = EmployeeData.getEmployees();
            employees.stream().sorted((o1, o2) -> o1.getAge() - o2.getAge()).forEach(System.out :: println);
        }

}
